extends EnemyBase

enum State {
	IDLE,
	PATROL,
	CHASE,
	ATTACK1,  # 普通攻击
	ATTACK2,  # 诅咒攻击
	ATTACK3,  # 扔炸弹
	CURSE_CAST,  # 施放诅咒
	HURT,
	DEAD
}

@export var attack1_damage: float = 25.0
@export var attack2_damage: float = 12.0
@export var bomb_damage: float = 35.0
@export var curse_damage: float = 15.0
@export var attack_cooldown: float = 2.5
@export var curse_cooldown: float = 5.0
@export var patrol_range: float = 120.0
@export var curse_duration: float = 5.0
@export var bomb_scene: PackedScene  # 炸弹场景
@export var health_bar_scene: PackedScene = preload("res://scenes/monster_health_bar.tscn")

var current_state: State = State.IDLE
var target: Node2D = null
var patrol_location: Vector2 = Vector2.ZERO
var initial_position: Vector2
var can_attack: bool = true
var can_curse: bool = true
var curse_particles: GPUParticles2D = null
var facing_right: bool = true
var attack_type: int = 1  # 1: 普通攻击, 2: 诅咒攻击, 3: 扔炸弹
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var knockback_force = Vector2.ZERO
var is_invincible = false
var invincible_timer = 0.0
const INVINCIBLE_TIME = 0.5
var attack_ready = false


@onready var attack_hitbox: Area2D = $AttackHitbox
@onready var hurt_box: Area2D = $HurtBox

func _ready():
	super._ready()  # 调用父类的_ready
	initial_position = global_position
	_update_patrol_location()
	_setup_curse_particles()
	animated_sprite.play("idle")
	
	# 设置碰撞层
	collision_layer = 4  # 敌人层 (第3层)
	collision_mask = 2  # 与地面层碰撞（第2层）
	
	# 设置攻击检测区域的碰撞层
	if attack_hitbox:
		attack_hitbox.collision_layer = 8  # 敌人攻击层 (第4层)
		attack_hitbox.collision_mask = 2   # 检测玩家层 (第2层)
	
	# 设置受伤检测区域的碰撞层
	if hurt_box:
		hurt_box.collision_layer = 16  # 敌人受伤层 (第5层)
		hurt_box.collision_mask = 32   # 检测玩家攻击层 (第6层)
	
	# 创建血条
	_setup_health_bar()

func _setup_health_bar():
	health_bar = health_bar_scene.instantiate()
	add_child(health_bar)
	health_bar.position = Vector2(-20, -30)  # 调整血条位置
	health_bar._initialize_health_bar()

func _physics_process(delta):
	if is_invincible:
		invincible_timer -= delta
		if invincible_timer <= 0:
			is_invincible = false
			modulate.a = 1.0
	
	# 应用重力
	if not is_on_floor():
		velocity.y += gravity * delta
		# 如果掉出地图太远，重置位置
		if global_position.y > 1000:  # 根据你的地图大小调整这个值
			global_position = initial_position
			velocity = Vector2.ZERO
	else:
		# 在地面上时重置垂直速度
		velocity.y = 0
	
	# 处理击退力
	if knockback_force != Vector2.ZERO:
		velocity = knockback_force
		knockback_force = knockback_force.move_toward(Vector2.ZERO, delta * 1000)
		# 如果击退力很小，直接清零
		if knockback_force.length() < 10:
			knockback_force = Vector2.ZERO
	
	# 更新血条
	if health_bar:
		health_bar.set_health(current_health, max_health)
	
	# 根据当前状态处理行为
	match current_state:
		State.IDLE:
			_process_idle_state(delta)
		State.PATROL:
			_process_patrol_state(delta)
		State.CHASE:
			_process_chase_state(delta)
		State.ATTACK1:
			_process_attack1_state(delta)
		State.ATTACK2:
			_process_attack2_state(delta)
		State.ATTACK3:
			_process_attack3_state(delta)
		State.CURSE_CAST:
			_process_curse_cast_state(delta)
		State.HURT:
			_process_hurt_state(delta)
		State.DEAD:
			_process_dead_state(delta)
	
	# 更新朝向
	if velocity.x != 0:
		facing_right = velocity.x > 0
		animated_sprite.flip_h = !facing_right
	
	# 确保移动和碰撞检测
	move_and_slide()
	
	# 额外的地面检测
	if is_on_floor():
		velocity.y = 0  # 确保在地面上时垂直速度为0
	
	# 调试输出
	if Engine.get_physics_frames() % 60 == 0:  # 每60帧输出一次
		print("诅咒哥布林状态: ", State.keys()[current_state], ", 速度: ", velocity, ", 位置: ", global_position)

func _process_idle_state(_delta):
	if not is_on_floor():
		return
		
	velocity.x = 0
	if target:
		current_state = State.CHASE
		animated_sprite.play("run")
	elif randf() < 0.01:
		current_state = State.PATROL
		animated_sprite.play("run")
		_update_patrol_location()
	elif not animated_sprite.animation == "idle":
		animated_sprite.play("idle")

func _process_patrol_state(_delta):
	if not is_on_floor():
		return
		
	if target:
		current_state = State.CHASE
		animated_sprite.play("run")
		return
	
	var direction = (patrol_location - global_position).normalized()
	velocity.x = direction.x * move_speed
	
	# 防止原地踏步 - 如果距离巡逻点还有一段距离但速度接近0，强制设置速度
	if global_position.distance_to(patrol_location) > 20 and abs(velocity.x) < 10:
		velocity.x = direction.x * move_speed
		print("修正诅咒哥布林巡逻速度: ", velocity.x)
	
	if global_position.distance_to(patrol_location) < 10:
		current_state = State.IDLE
		animated_sprite.play("idle")
		velocity.x = 0  # 确保停止移动

func _process_chase_state(_delta):
	if not is_on_floor():
		return
		
	if not target:
		current_state = State.IDLE
		animated_sprite.play("idle")
		velocity.x = 0  # 确保停止移动
		return
	
	var direction = (target.global_position - global_position).normalized()
	
	# 确保水平方向有足够的速度
	velocity.x = direction.x * move_speed * 1.5
	
	# 防止原地踏步 - 如果目标在右边但速度为0或负，或目标在左边但速度为0或正，强制设置速度
	if (direction.x > 0 and velocity.x <= 0) or (direction.x < 0 and velocity.x >= 0):
		velocity.x = direction.x * move_speed * 1.5
		print("修正诅咒哥布林速度: ", velocity.x)
	
	var distance = global_position.distance_to(target.global_position)
	if can_attack and distance < 200:  # 只要在攻击范围内就开始攻击
		if distance < 50:  # 近距离使用普通攻击
			attack_type = 1
			current_state = State.ATTACK1
			animated_sprite.play("attack1")
			attack_ready = false
			velocity.x = 0  # 攻击时停止移动
		elif distance < 100:  # 中距离使用诅咒攻击
			attack_type = 2
			current_state = State.ATTACK2
			animated_sprite.play("attack2")
			attack_ready = false
			velocity.x = 0  # 攻击时停止移动
		else:  # 远距离扔炸弹
			attack_type = 3
			current_state = State.ATTACK3
			animated_sprite.play("attack3")
			attack_ready = false
			velocity.x = 0  # 攻击时停止移动
	elif not animated_sprite.animation == "run":
		animated_sprite.play("run")

func _process_attack1_state(_delta):
	velocity = Vector2.ZERO
	if not attack_ready and animated_sprite.frame >= 4:  # 在动画第4帧时造成伤害
		attack_ready = true
		_perform_attack1()

func _process_attack2_state(_delta):
	velocity = Vector2.ZERO
	if not attack_ready and animated_sprite.frame >= 5:  # 在动画第5帧时施放诅咒
		attack_ready = true
		_perform_attack2()

func _process_attack3_state(_delta):
	velocity = Vector2.ZERO
	if not attack_ready and animated_sprite.frame >= 5:  # 在动画第5帧时标记准备扔炸弹
		attack_ready = true
		# 注意：不在这里实例化炸弹，而是在动画结束时

func _process_curse_cast_state(_delta):
	velocity = Vector2.ZERO
	if can_curse and target:
		_cast_curse()

func _process_hurt_state(_delta):
	velocity = Vector2.ZERO
	if not animated_sprite.animation == "hurt":
		animated_sprite.play("hurt")

func _process_dead_state(_delta):
	velocity = Vector2.ZERO
	if not animated_sprite.animation == "death":
		animated_sprite.play("death")
	# 确保死亡状态下不会被重新激活
	set_physics_process(false)
	set_process(false)

func _setup_curse_particles():
	curse_particles = GPUParticles2D.new()
	# 在这里设置粒子系统的属性
	add_child(curse_particles)
	curse_particles.emitting = false

func _update_patrol_location():
	var random_offset = Vector2(
		randf_range(-patrol_range, patrol_range),
		0  # 只在水平方向巡逻
	)
	patrol_location = initial_position + random_offset

func _perform_attack1():
	can_attack = false
	if target and target.has_method("take_damage") and attack_ready:
		target.take_damage(attack1_damage, global_position)
	$AttackTimer.start(attack_cooldown)

func _perform_attack2():
	can_attack = false
	if target and target.has_method("apply_curse") and attack_ready:
		target.apply_curse(curse_damage, curse_duration)
	$AttackTimer.start(attack_cooldown * 1.2)

func _perform_attack3():
	can_attack = false
	# 不在这里实例化炸弹，而是在动画结束时
	$AttackTimer.start(attack_cooldown * 1.5)  # 扔炸弹冷却时间更长

func _cast_curse():
	can_curse = false
	if target and target.has_method("apply_curse"):
		target.apply_curse(curse_damage, curse_duration)
	elif target and target.has_method("take_damage"):
		# 如果目标没有诅咒方法，就造成直接伤害
		target.take_damage(curse_damage * curse_duration, global_position)
	
	if curse_particles:
		curse_particles.emitting = true
	
	$CurseTimer.start(curse_cooldown)

func take_damage(amount: float, attacker_position: Vector2 = Vector2.ZERO, is_quick_slash: bool = false) -> void:
	if current_state == State.DEAD or is_invincible:
		return
	
	current_health -= amount
	is_invincible = true
	invincible_timer = INVINCIBLE_TIME
	modulate.a = 0.5
	
	# 更新血条
	if health_bar:
		health_bar.set_health(current_health, max_health)
	
	# 计算击退方向和力度
	if attacker_position != Vector2.ZERO:
		var knockback_direction = (global_position - attacker_position).normalized()
		
		if is_quick_slash:
			# 疾风斩带来更强的击退效果
			knockback_force = knockback_direction * 400  # 更强的水平击退
			knockback_force.y = -250  # 更高的向上力度
		else:
		knockback_force = knockback_direction * 300
		knockback_force.y = -200  # 添加向上的力
	
	if current_health <= 0:
		current_state = State.DEAD
		animated_sprite.play("death")
		# 禁用碰撞
		$CollisionShape2D.set_deferred("disabled", true)
		if attack_hitbox:
			attack_hitbox.set_deferred("monitoring", false)
			attack_hitbox.set_deferred("monitorable", false)
		if hurt_box:
			hurt_box.set_deferred("monitoring", false)
			hurt_box.set_deferred("monitorable", false)
		# 确保在动画结束后销毁
		if not animated_sprite.animation_finished.is_connected(_on_death_animation_finished):
			animated_sprite.animation_finished.connect(_on_death_animation_finished)
	else:
		# 对于疾风斩，跳过hurt状态，只应用视觉效果
		if is_quick_slash:
			# 闪光效果
			var tween = create_tween()
			tween.tween_property(self, "modulate", Color(2.0, 1.5, 1.5, 0.7), 0.1)
			tween.tween_property(self, "modulate", Color(1, 1, 1, 0.5), 0.1)
	else:
		current_state = State.HURT
		animated_sprite.play("hurt")
		$StateTimer.start(0.3)

func _on_death_animation_finished():
	if animated_sprite.animation == "death":
		queue_free()

func _on_detection_area_body_entered(body):
	if body.is_in_group("player"):
		target = body
		animated_sprite.play("run")

func _on_detection_area_body_exited(body):
	if body == target:
		target = null
		animated_sprite.play("idle")

func _on_attack_timer_timeout():
	can_attack = true
	if target:
		var distance = global_position.distance_to(target.global_position)
		if distance < 40:
			attack_type = randi_range(1, 2)
			current_state = State.ATTACK1 if attack_type == 1 else State.ATTACK2
			animated_sprite.play("attack" + str(attack_type))
		elif distance < 150:
			if can_curse and randf() < 0.4:
				current_state = State.CURSE_CAST
				animated_sprite.play("attack2")
			else:
				attack_type = 3
				current_state = State.ATTACK3
				animated_sprite.play("attack3")
		else:
			current_state = State.CHASE
			animated_sprite.play("run")

func _on_curse_timer_timeout():
	can_curse = true
	if target and global_position.distance_to(target.global_position) < 150:
		current_state = State.CURSE_CAST
		animated_sprite.play("attack2")

func _on_state_timer_timeout():
	if current_state == State.HURT:
		current_state = State.CHASE if target else State.IDLE
		animated_sprite.play("run" if target else "idle")

func _on_hurt_box_area_entered(area: Area2D):
	if area.is_in_group("player_attack"):
		var damage = area.get_parent().get("attack_damage") if area.get_parent().has_method("get") else 10.0
		
		# 检查是否是疾风斩攻击
		var is_quick_slash = false
		if area.get_parent() and area.get_parent().has_method("is_player") and area.get_parent().get("is_quick_slashing") != null:
			is_quick_slash = area.get_parent().is_quick_slashing
		
		take_damage(damage, area.global_position, is_quick_slash)

func _on_animated_sprite_animation_finished():
	match animated_sprite.animation:
		"attack1", "attack2":
			attack_ready = false
			if target:
				var distance = global_position.distance_to(target.global_position)
				if distance < 200 and can_attack:  # 如果还在攻击范围内且可以攻击
					if distance < 50:  # 近距离使用普通攻击
						attack_type = 1
						current_state = State.ATTACK1
						animated_sprite.play("attack1")
					elif distance < 100:  # 中距离使用诅咒攻击
						attack_type = 2
						current_state = State.ATTACK2
						animated_sprite.play("attack2")
					else:  # 远距离扔炸弹
						attack_type = 3
						current_state = State.ATTACK3
						animated_sprite.play("attack3")
				else:
					current_state = State.CHASE
					animated_sprite.play("run")
			else:
				current_state = State.IDLE
				animated_sprite.play("idle")
		"attack3":
			# 在扔炸弹动画结束时实例化炸弹
			if target and bomb_scene and attack_ready:
				var bomb = bomb_scene.instantiate()
				
				# 设置炸弹位置 - 从哥布林手中扔出
				var spawn_offset = Vector2(20, -10)  # 调整这个值以匹配动画
				if !facing_right:
					spawn_offset.x = -spawn_offset.x
				bomb.global_position = global_position + spawn_offset
				
				# 计算目标位置 - 直接瞄准玩家位置
				var target_pos = target.global_position
				bomb.target = target_pos
				bomb.damage = bomb_damage
				
				# 设置炸弹动画 - 使用诅咒版本
				if bomb.animated_sprite:
					bomb.animated_sprite.play("bomb1_ashcurse")  # 使用诅咒哥布林的炸弹动画
					bomb.is_ashcurse = true  # 明确设置为诅咒炸弹
					
				# 添加到场景中
				get_parent().add_child(bomb)
				print("诅咒哥布林扔出炸弹，目标位置: ", target_pos)
			
			attack_ready = false  # 重置攻击状态
			if target:
				current_state = State.CHASE
				animated_sprite.play("run")
			else:
				current_state = State.IDLE
				animated_sprite.play("idle")
		"death":
			queue_free()  # 确保在死亡动画结束后销毁实例
